/*
 *  cstr.hpp - C string wrapper and compare class for hash
 *
 *    Copyright (c) 2001-2006, Luxena Company. All rights reserved.
 *
 *  Purpose:
 *
 */

#ifndef __CSTR_H_
#define __CSTR_H_

#include <string.h>


/////////////////////////////////////////////////////////////////////////////
// C string wrapper

class _cstr_t
{
private:
	char *m_p;
	void set(const char *p) { if (p != 0) m_p = strdup(p); else m_p = 0; }

public:
	_cstr_t() { m_p = 0; };
	_cstr_t(size_t size) { m_p = static_cast<char *>(malloc(size)); }
	_cstr_t(const char *p) { set(p); }
	_cstr_t(const _cstr_t& str) { set(str.m_p); }
	~_cstr_t() { free(m_p);	}
	_cstr_t& operator = (const char *p) { free(m_p); set(p); return *this; }
	_cstr_t & operator = (const _cstr_t& str) { return *this = str.m_p; }
	operator char * () const { return m_p; };
	void attach (char *p) { free(p); m_p = p; };
	char * detach () { char *p = m_p; m_p = 0; return p; };
};

class compare_cstr
{
public:
	static int delta(const char *left, const char *right)
	{
		return strcmp(left, right);
	}
	static unsigned int evaluate(const char *key, long tablesize)
	{
		unsigned int result = 0;
		while (*key != 0)
			result = ((result << 1) ^ tablesize) + *key++;
		return result % tablesize;
	}
};

#endif
